/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dao.exceptions.NonexistentEntityException;
import java.util.List;
//import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import persistencia.Usuario;
/*import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.criterion.*;
import org.hibernate.cfg.*;*/

/**
 *
 * @author MALLO-M
 */
public class UsuarioJpaController {

    public UsuarioJpaController() {
        System.out.println("constructor UsuarioJpaController1");
        emf = Persistence.createEntityManagerFactory("UPSAMV2-ejbPU");
        System.out.println("constructor UsuarioJpaController2");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public boolean findEmail(String email) {
        EntityManager em = getEntityManager();
        System.out.println("find --> " + email);
        em.getTransaction().begin();
        List list = em.createQuery("SELECT u FROM Usuario u WHERE u.email LIKE :emailUsuario").setParameter("emailUsuario", email).getResultList();
        System.out.println("create list --> " + list.size());
        if (list.isEmpty()) {
            return false;
        } else {
            return true;
        }
    }

    public Usuario findPassword(String email,String password) {
        EntityManager em = getEntityManager();
        em.getTransaction().begin();
        List list = em.createQuery("SELECT u FROM Usuario u WHERE u.email LIKE :emailUsuario AND u.password LIKE :passwordUsuario").setParameter("emailUsuario", email).setParameter("passwordUsuario", password).getResultList();
        Usuario usuario;
        if (list.size() == 0) {
            System.err.println("Usuario no coincide");
            usuario=new Usuario();
            System.err.println("Antes de retornar");
            return usuario;
        } else {
            System.err.println("Usuario coincide");
            usuario = (Usuario) list.get(0);
            return usuario;
            //return usu.getPassword();
        }
    }

    public void create(Usuario usuario) {
        EntityManager em = null;
        try {
            em = getEntityManager();
            System.out.println("create --> " + usuario.getEmail());

            em.getTransaction().begin();
            //List list = em.createQuery("SELECT c FROM Usuario c WHERE c.email LIKE :email").setParameter("email", usuario.getEmail()).setMaxResults(10).getResultList();
            //System.out.println("create list --> " + list.size());
            List list = em.createQuery("SELECT u FROM Usuario u WHERE u.email LIKE :emailUsuario").setParameter("emailUsuario", usuario.getEmail()).getResultList();
            System.out.println("create list --> " + list.size());
            if (list.size() == 0) {
                //Query q = em.createQuery("select email from usuario where email=l");
                //System.out.println("consulta q --> " + q.);
                //String sql = "select COUNT(*) from USUARIO where EMAIL='" +usuario.getEmail()+"';";
                String sql = "select count(*) from usuario where email='l'";
                em.persist(usuario);
                em.getTransaction().commit();
            } else {
                System.out.println("Email ya existente.");
            }
        } catch (Exception e) {
            System.err.println("Error en create --> " + e.getMessage());
            e.printStackTrace();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }
    public void edit(Usuario usuario) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            System.err.println("edit");
            em = getEntityManager();
            em.getTransaction().begin();
            usuario = em.merge(usuario);
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = usuario.getId();
                if (findUsuario(id) == null) {
                    throw new NonexistentEntityException("The usuario with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Usuario usuario;
            try {
                usuario = em.getReference(Usuario.class, id);
                usuario.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The usuario with id " + id + " no longer exists.", enfe);
            }
            em.remove(usuario);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Usuario> findUsuarioEntities() {
        return findUsuarioEntities(true, -1, -1);
    }

    public List<Usuario> findUsuarioEntities(int maxResults, int firstResult) {
        return findUsuarioEntities(false, maxResults, firstResult);
    }

    private List<Usuario> findUsuarioEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Usuario as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Usuario findUsuario(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Usuario.class, id);
        } finally {
            em.close();
        }
    }

    public int getUsuarioCount() {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select count(o) from Usuario as o");
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
}
